import classNames from 'classnames'
import React, { useEffect, useRef, useState } from 'react'
import { useDispatch } from 'react-redux'
import { todoDel, todoChangeDone, todoModifyName } from '../../store/actions/todo'

export default function TodoItem({ item }) {
  const [dbId, setDbId] = useState('')
  const [currName, setCurrName] = useState('')
  const iptRef = useRef()
  const dispatch = useDispatch()

  function delTodo(id) {
    dispatch(todoDel(id))
  }

  function changeDone(id) {
    dispatch(todoChangeDone(id))
  }

  function handleDbClick(id, name) {
    setDbId(id)
    setCurrName(name)
  }

  useEffect(() => {
    iptRef.current.focus()
  }, [dbId])

  function handleBlur() {
    setDbId('')
  }

  function handleEditChange(e) {
    setCurrName(e.target.value)
  }

  function handleKeyUp(e) {
    if (e.key === 'Escape') {
      handleDbClick('', '')
      return
    }
    if (currName.trim().length === 0) return
    if (e.keyCode === 13) {
      dispatch(todoModifyName({id: item.id, name: currName}))
      handleDbClick('', '')
    }
  }

  return (
    <li className={classNames({ completed: item.done, editing: item.id === dbId })} key={item.id}>
      <div className="view">
        <input
          className="toggle"
          type="checkbox"
          checked={item.done}
          onChange={() => {
            changeDone(item.id)
          }}
        />
        <label onDoubleClick={() => handleDbClick(item.id, item.name)}>{item.name}</label>
        <button className="destroy" onClick={() => delTodo(item.id)}></button>
      </div>
      <input
        className="edit"
        value={currName}
        onChange={handleEditChange}
        ref={iptRef}
        onBlur={handleBlur}
        onKeyUp={handleKeyUp}
      />
    </li>
  )
}
